﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using CRL.Core.ApiProxy;

namespace ApiProxyTest
{
    public static class ApiProxyExtensions
    {
        static bool _RegisterApiHost = false;
        /// <summary>
        /// 注册API Host
        /// </summary>
        /// <param name="host"></param>
        public static void RegisterApiHost(this IServiceCollection services, HostInfo host, string consulUrl = "")
        {
            Extensions.RegisterApiHost(host, consulUrl);
            services.AddHttpClient(host.Name, config =>
             {
             });
            _RegisterApiHost = true;
        }


        static void RegisterApiClient<T>(this IServiceCollection services, Func<string, Dictionary<string, object>> headAction = null) where T : class
        {
            var attr = typeof(T).GetCustomAttribute<ServiceAttribute>();
            var hostUrl = attr?.HostUrl;
            var hostName = attr?.HostName;
            if (!_RegisterApiHost)
            {
                services.AddHttpClient(hostUrl, config =>
                {
                });
            }
            services.AddTransient(s =>
            {
                var fac = s.GetService<IHttpClientFactory>();
                var client = fac?.CreateClient(_RegisterApiHost ? hostName : hostUrl);
                return Extensions.GetClient<T>(headAction, client);
            });
        }

        /// <summary>
        /// 注册客户端
        /// </summary>
        /// <param name="services"></param>
        /// <param name="headAction"></param>
        /// <param name="assemblies"></param>
        public static void RegisterApiClient(this IServiceCollection services, Func<string, Dictionary<string, object>> headAction = null, params Assembly[] assemblies)
        {
            foreach (var assembyle in assemblies)
            {
                var types = assembyle.GetTypes();
                foreach (var type in types)
                {
                    var attr = type.GetCustomAttribute<ServiceAttribute>();
                    if (attr == null)
                    {
                        continue;
                    }
                    var method = typeof(ApiProxyExtensions).GetMethod(nameof(RegisterApiClient), BindingFlags.NonPublic | BindingFlags.Static);
                    var result = method.MakeGenericMethod(new Type[] { type }).Invoke(null, new object[] { services, headAction });
                }
            }
        }
    }
}
